<template>
  <div>
    <h1>登录页面</h1>
  </div>
  <el-button @click="goRegire()">注册</el-button>
  <div style="width: 1200px; margin: auto; margin-top: 150px">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="用户手机号" prop="userMobile" style="width: 300px">
        <el-input v-model="ruleForm.userMobile" />
      </el-form-item>
      <el-form-item label="用户密码" prop="userPass" style="width: 300px">
        <el-input v-model="ruleForm.userPass" />
      </el-form-item>
      <el-form-item style="margin-left: 100px">
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
const ruleFormRef = ref<FormInstance>();
const router = useRouter();
import { userLogin } from "@/api/api";
import { useRouter } from "vue-router";
const ruleForm = ref({
  userMobile: "",
  userPass: "",
});

const rules = ref<FormRules>({
  userMobile: [
    { required: true, message: "输入手机号", trigger: "blur" },
    {
      pattern:
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
      message: "手机号格式不正确",
      trigger: "blur",
    },
  ],
  userPass: [{ required: true, message: "输入密码", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");

      userLogin(ruleForm.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("登录成功");

          let user = res.data.data;
          let token = user.token;

          sessionStorage.setItem("user", JSON.stringify(user));
          sessionStorage.setItem("token", token);

          router.push("/home");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const goRegire = () => {
  router.push("/regire");
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style scoped></style>
